/**
 * @Author: zkz
 * @CreateTime: 2025-09-11 16:23:59
 * @Description: 和用户模块相关的状态管理
 */
import { createSlice } from '@reduxjs/toolkit';
//这里引入的setToken方法与user.js中的方法重名了，所以as一个新的名称_setToken
import { setToken as _setToken, getToken, removeToken } from '@/utils/token';
import { loginAPI, getUserInfoAPI } from '@/api/user';
const userStore = createSlice({
    name: 'users',
    //数据状态
    initialState: {
        token: getToken() || '',//token持久化存储
        userInfo: {},//用户信息
    },
    //同步修改数据状态的函数
    reducers: {
        setToken: (state, action) => {
            state.token = action.payload;
            //localStorage存储token持久化
            _setToken(action.payload);
        },
        setUseInfo: (state, action) => {
            state.userInfo = action.payload;
        },
        clearUserInfo: (state) => {
            state.userInfo = {};
            state.token = '';
            removeToken();
        }
    },
})
// 结构actionsCreater
const { setToken, setUseInfo, clearUserInfo } = userStore.actions;
// 结构reducer
const userReducer = userStore.reducer;

//异步方法 完成登录获取token
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await loginAPI(loginForm)
        dispatch(setToken(res.data.token))
    }
}

//异步方法 获取用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getUserInfoAPI()
        dispatch(setUseInfo(res.data))
    }
}




export { setToken, fetchLogin, fetchUserInfo, clearUserInfo };
export default userReducer;